package com.snake.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JLabel;

import com.snake.entity.Food;
import com.snake.entity.Ground;
import com.snake.entity.Snake;
import com.snake.listener.SnakeListener;
import com.snake.util.Constant;
import com.snake.view.GamePanel;

public class Controller extends KeyAdapter implements SnakeListener{
	private Snake snake;
	private Ground ground;
	private Food food;
	private GamePanel gamePanel;
	
	public Controller(Snake snake, Ground ground, Food food, GamePanel gamePanel) {
		super();
		this.snake = snake;
		this.ground = ground;
		this.food = food;
		this.gamePanel = gamePanel;
	}

	public void keyPressed(KeyEvent e) {
		
		switch(e.getKeyCode()){
		case KeyEvent.VK_UP:
			System.out.println("UP=======================");
			snake.changeDirection(Constant.UP);
			break;
	    case KeyEvent.VK_DOWN:
	    	System.out.println("DOWN=======================");
		    snake.changeDirection(Constant.DOWN);
		    break;
        case KeyEvent.VK_LEFT:
        	System.out.println("LEFT=======================");
	        snake.changeDirection(Constant.LEFT);
	        break;
	    case KeyEvent.VK_RIGHT:
	    	System.out.println("RIGHT=======================");
	        snake.changeDirection(Constant.RIGHT);
	        break;
	     }
	}

	public void snakeMoved(Snake snake) throws Exception {
		if(food.isEatFood(snake)){
			snake.eatFood();
			food.newFood(ground.getPoint(snake.getBody()));
		}
		if(ground.isEatRock(snake)){
			snake.death();
			gameOver();
		}
		if(snake.isEatBody()){
			snake.death();
			gameOver();
		}
		gamePanel.display(snake, food, ground);
	}
	
	private void gameOver(){
		JLabel label = gamePanel.label;
		label.setText("GAME OVER");
		label.setForeground(Color.RED);
		label.setFont(new Font(null, Font.ITALIC, 50));
	}
	
	public void newGame(){
		snake.start();
		food.newFood(ground.getPoint(snake.getBody()));
		
	}
	
}
